package com.yl.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wlf
 * @since 2022/8/9
 */
public class TimerUtil {

    // 语音告警同一被叫号码60秒内最多发送1条
    private static final Map<String, TimeInterval> voiceTimer = new ConcurrentHashMap<>();
    // 缓存测点状态更新的频率,最快一秒更新一次 key为 TPL_STA_TARGET TPL_STA_TYPE
    private static final Map<String, TimeInterval> statusTimer = new ConcurrentHashMap<>();

    /**
     * 判断某个手机号的发送频率
     * 【发送间隔60秒】
     *
     * @param phone 手机号
     */
    public static boolean voiceTimer(String phone) {
        boolean res = true;
        int interval = 60;
        TimeInterval timer = getTimer(voiceTimer, phone);
        if (null != timer) {
            if (timer.intervalSecond() <= interval) {
                res = false;
            }
        }
        return res;
    }

    /**
     * 根据配置的数据间隔，控制缓存测点状态更新的频率
     * 最快一秒更新一次
     * @param key TPL_STA_TARGET | TPL_STA_TYPE
     * @param interval 数据间隔
     */
    public static boolean statusTimer(String key, int interval) {
        boolean res = true;
        TimeInterval timer = getTimer(statusTimer, key);
        if (null != timer) {
            if (timer.intervalSecond() <= interval) {
                res = false;
            }
        }
        return res;
    }

    /**
     * 获取某个手机号的定时器
     */
    private static TimeInterval getTimer(Map<String, TimeInterval> timer, String key) {
        return timer.get(key);
    }

    /**
     * 给某个手机号添加定时器
     *
     * @param phone 手机号
     */
    public static void setVoiceTimer(String phone) {
        voiceTimer.put(phone, DateUtil.timer());
    }

    /**
     * 给某个手机号添加定时器
     *
     * @param key TPL_STA_TARGET | TPL_STA_TYPE
     */
    public static void setStatusTimer(String key) {
        statusTimer.put(key, DateUtil.timer());
    }

}
